/**
 * Title:        流程监控数据监测
 * Company:      泛微软件
 */


package checkDetail;

import general.BaseBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.workflow.ruleDesign.ExpressionBean;
import weaver.workflow.ruleDesign.Expressions;
import weaver.workflow.workflow.WorkTypeComInfo;



public class RuleExpressionBaseCheck extends BaseBean implements CheckBase  {

    private WorkTypeComInfo workTypeComInfo= new WorkTypeComInfo();
    private RecordSet rset = new RecordSet();
    private RecordSet rs = new RecordSet();
    @Override
    public JSONObject checkData(HashMap dataMap) {
        setRecordSet();
        (new BaseBean()).writeLog("RuleExpressionBaseCheck  start");

        boolean isoracle = (recordSet.getDBType()).equals("oracle") ;
        List resultList = new ArrayList();
        String result = "";

        String setsql = "";
        String selectSql = "";
        String selectSql1 = "";

        if(isoracle){
            rs.executeSql("select * from rule_expressions where id >0 and ',' || expids || ',' like ('%,' || id ||',%')");
        }else{
            rs.executeSql("select * from rule_expressions where id >0 and ',' + expids + ',' like ('%,' + cast(id as varchar) +',%')");
        }
        if(rs.next()){
            result = resultNeedFix;
            Map resultMap = new HashMap<String,String>();
            resultMap.put("showMessage","数据库中存在"+ rs.getCounts() + "条ID冲突的数据，请修复");
            resultMap.put("deleteexpressions","deleteexpressions");
            resultMap.put("buttonname","修复");
            resultList.add(resultMap);
        }else{
            result = resultOk;
            RecordSetTrans rst=new RecordSetTrans();
            rst.setAutoCommit(false);
            try {
            
            String selectsql = " select RULEID, DATAFIELD, DATAFIELDTEXT, COMPAREOPTION1, COMPAREOPTION2, HTMLTYPE, TYPEHRM, FIELDTYPE, VALUETYPE, PARAMTYPE, cast(elementvalue1 as varchar(4000)), cast(ELEMENTLABEL1 as varchar(4000)), ELEMENTVALUE2, DBTYPE, REDIUS, MEETCONDITION, NODEID, JINGDU, WEIDU "+
                         " from RULE_EXPRESSIONBASE group by RULEID, DATAFIELD, DATAFIELDTEXT, COMPAREOPTION1, COMPAREOPTION2, HTMLTYPE, TYPEHRM, FIELDTYPE, VALUETYPE, PARAMTYPE, cast(elementvalue1 as varchar(4000)), cast(ELEMENTLABEL1 as varchar(4000)), ELEMENTVALUE2, DBTYPE, REDIUS, MEETCONDITION, NODEID, JINGDU, WEIDU "+
                         " having  count(1) > 1";
            
            ArrayList<String> expList = new ArrayList<String>();
            ArrayList<String> expbaseList = new ArrayList<String>();
            rs.executeSql(selectsql);//查询RULE_EXPRESSIONBASE重复数据
            boolean errExists = false;
            while(rs.next()) {
                int ruleid = Util.getIntValue(rs.getString("RULEID"), 0);
                if(ruleid != 0){
                    rset.executeSql("select id from rule_expressions where ruleid=" + ruleid + " ORDER BY id desc");
                    if (rset.next()) {
                        int expid = Util.getIntValue(rset.getString("id"),0);
                        if(expid != 0){
                            getExpressions(expid,expList,expbaseList);
                            expList.add(expid+"");
                            String exptostring = listToString(expList);
                            String ebasetostring = listToString(expbaseList);
                            if(!"".equals(exptostring)){
                                Map resultMap = new HashMap<String,String>();
                                String strsqlClause = Util.getSubINClause(exptostring, "id", "not in");
                                String selexp = " select 1 from rule_expressions where ruleid = "+ruleid+" and "+strsqlClause;
                                //out.print("deleteexp = "+deleteexp+"<br>");
                                recordSet.executeSql(selexp);
                                if(recordSet.next()){
                                    errExists = true;
                                    resultMap.put("showMessage","expression数据库中存在冗余数据，请修复");
                                    resultMap.put("buttonname","修复");
                                    resultMap.put("ruleid",ruleid);
                                    resultList.add(resultMap);
                                    break;
                                }
                            }
                            if(!"".equals(ebasetostring)){
                                Map resultMap = new HashMap<String,String>();
                                String strsqlClause1 = Util.getSubINClause(ebasetostring, "id", "not in");
                                String selebase = " select 1 from rule_expressionbase where ruleid = "+ruleid+" and "+strsqlClause1;
                                //out.print("deleteexp = "+deleteexp+"<br>");
                                recordSet.executeSql(selebase);
                                if(recordSet.next()){
                                    errExists = true;
                                    resultMap.put("showMessage","expression数据库中存在冗余数据，请修复");
                                    resultMap.put("buttonname","修复");
                                    resultMap.put("ruleid",ruleid);
                                    resultList.add(resultMap);
                                    break;
                                }
                            }
                        }
                    }
                }
                expList.clear();
                expbaseList.clear();
            }
            if(errExists){
                result = resultNeedFix;
            }
            }catch (Exception e) {
                resultList.add("重复数据检测失败！");
                e.printStackTrace();
            }

        }
        (new BaseBean()).writeLog("RuleExpressionBaseCheck  end");
        return formatReturnJsonCheck(result, resultList,this);
    }

    @Override
    public JSONObject fixData(HashMap dataMap) {

        setRecordSet();
        boolean isoracle = (recordSet.getDBType()).equals("oracle") ;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");//设置日期格式
        String nowdata = "";
        nowdata = df.format(new Date());
        String baksql0 = "";
        String baksql1 = "";
        String baksql2 = "";
        if(isoracle){
            baksql1 = " create table rule_expressionbase_"+nowdata+" as select * from rule_expressionbase ";
            baksql2 = " create table rule_expressions_"+nowdata+" as select * from rule_expressions ";
        }else{
            baksql1 = " select * into rule_expressionbase_"+nowdata+" from rule_expressionbase ";
            baksql2 = " select * into rule_expressions_"+nowdata+" from rule_expressions ";
        }
        //备份表rule_expressionbase、rule_expressions
        //rs.writeLog("备份表rule_expressionbase_"+nowdata+"：：：表rule_expressions_"+nowdata+"成功！"+"</br>");
        
        //rs.executeSql(baksql1);
        //rs.executeSql(baksql2);
        
        String result = "";
        List resultList = new ArrayList();

        String divid = (String)dataMap.get("divid");
        result = resultOk;
        if(isoracle){
            rs.executeSql("update rule_expressions set id = id * -1 where id >0 and ',' || expids || ',' like ('%,' || id ||',%')");
        }else{
            rs.executeSql("update rule_expressions set id = id * -1  where id >0 and ',' + expids + ',' like ('%,' + cast(id as varchar) +',%')");
        }

        if(isoracle){
            rs.executeSql("select * from rule_expressions where id >0 and ',' || expids || ',' like ('%,' || id ||',%')");
        }else{
            rs.executeSql("select * from rule_expressions where id >0 and ',' + expids + ',' like ('%,' + cast(id as varchar) +',%')");
        }
        if(rs.next()){
            Map resultMap = new HashMap<String,String>();
            result = resultOk;
            resultMap.put("fixMessage","修复成功");
            resultMap.put("divid",divid);
            resultList.add(resultMap);
        }else{
            Map resultMap = new HashMap<String,String>();
            result = resultNeedFix;
            resultMap.put("fixMessage","修复失败");
            resultMap.put("divid",divid);
            resultList.add(resultMap);
        }
        RecordSetTrans rst=new RecordSetTrans();
        rst.setAutoCommit(false);
        try {
        
        String selectsql = " select RULEID, DATAFIELD, DATAFIELDTEXT, COMPAREOPTION1, COMPAREOPTION2, HTMLTYPE, TYPEHRM, FIELDTYPE, VALUETYPE, PARAMTYPE, cast(elementvalue1 as varchar(4000)), cast(ELEMENTLABEL1 as varchar(4000)), ELEMENTVALUE2, DBTYPE, REDIUS, MEETCONDITION, NODEID, JINGDU, WEIDU "+
                     " from RULE_EXPRESSIONBASE group by RULEID, DATAFIELD, DATAFIELDTEXT, COMPAREOPTION1, COMPAREOPTION2, HTMLTYPE, TYPEHRM, FIELDTYPE, VALUETYPE, PARAMTYPE, cast(elementvalue1 as varchar(4000)), cast(ELEMENTLABEL1 as varchar(4000)), ELEMENTVALUE2, DBTYPE, REDIUS, MEETCONDITION, NODEID, JINGDU, WEIDU "+
                     " having  count(1) > 1";
        
        ArrayList<String> expList = new ArrayList<String>();
        ArrayList<String> expbaseList = new ArrayList<String>();
        rs.executeSql(selectsql);//查询RULE_EXPRESSIONBASE重复数据
        boolean errExists = false;
        while(rs.next()) {
            int ruleid = Util.getIntValue(rs.getString("RULEID"), 0);
            if(ruleid != 0){
                rset.executeSql("select id from rule_expressions where ruleid=" + ruleid + " ORDER BY id desc");
                if (rset.next()) {
                    int expid = Util.getIntValue(rset.getString("id"),0);
                    if(expid != 0){
                        getExpressions(expid,expList,expbaseList);
                        expList.add(expid+"");
                        String exptostring = listToString(expList);
                        String ebasetostring = listToString(expbaseList);
                        if(!"".equals(exptostring)){
                            String strsqlClause = Util.getSubINClause(exptostring, "id", "not in");
                            String deleteexp = " delete from rule_expressions where ruleid = "+ruleid+" and "+strsqlClause;
                            //out.print("deleteexp = "+deleteexp+"<br>");
                            rst.executeUpdate(deleteexp);
                            Map resultMap = new HashMap<String,String>();
                            resultMap.put("fixMessage","修复成功");
                            resultMap.put("divid",divid);
                            resultList.add(resultMap);
                        }
                        if(!"".equals(ebasetostring)){
                            String strsqlClause1 = Util.getSubINClause(ebasetostring, "id", "not in");
                            String deleteebase = " delete from rule_expressionbase where ruleid = "+ruleid+" and "+strsqlClause1;
                            //out.print("deleteebase = "+deleteebase+"<br>");
                            rst.executeUpdate(deleteebase);
                            Map resultMap = new HashMap<String,String>();
                            resultMap.put("fixMessage","修复成功");
                            resultMap.put("divid",divid);
                            resultList.add(resultMap);
                        }
                    }
                }
            }
            expList.clear();
            expbaseList.clear();
        }
        rst.commit();
        }catch (Exception e) {
            result = resultNeedFix;
            resultList.add("修复失败");
            e.printStackTrace();
            rst.rollback();
        }
        result = resultOk;
        resultList.add("修复成功");
        
        needReload = "1";
        return checkData(dataMap);
    }

    @Override
    public String getClassName() {
        return "EXPRESSION数据检测";
    }

    @Override
    public String getClassDesc() {
        return "检测EXPRESSION的数据，检测是否有ID重复以及冗余的数据。";
    }
    
    private Expressions getExpressions(int expressionid,ArrayList<String> expList,ArrayList<String> expbaseList) {
        //获取表达式集合
        Expressions exps = Expressions.getExpressions(expressionid);
        if (exps != null) {
            //如果是表达式集合
            if (!"".equals(exps.getExpids())) {
                List<String> expsidsArray = Util.TokenizerString(exps.getExpids(), ",");
                //System.out.println("exps.getExpids() = "+exps.getExpids());
                for (int i=0; i<expsidsArray.size(); i++) {
                    expList.add((String)expsidsArray.get(i));
                    //System.out.println("expsidsArray.get(i) = "+expsidsArray.get(i));
                    getExpressions(Integer.parseInt((String)expsidsArray.get(i)), expList, expbaseList);
                }
            } else {
                expbaseList.add(exps.getExpbaseid() + "");
                ExpressionBean expBean = getExpressionBean(exps.getExpbaseid());
                exps.getChildrens().add(expBean);
            }
        }
        return exps;
    }
    private String listToString(ArrayList<String> stringList){
        if (stringList==null) {
            return "";
        }
        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(string);
        }
        return result.toString();
    }
    /**
     * 根据id获取表达式对象
     * @param expid
     * @return
     */
    public static ExpressionBean getExpressionBean(int expid) {
        ExpressionBean expbean = null;
        RecordSet rs = new RecordSet();
        int rulesrc = -1;
        String sql = "select rulesrc from rule_base where id=(select distinct ruleid from rule_expressionbase where id="+expid+")";
        rs.executeSql(sql);
        if(rs.next()){
            rulesrc = Util.getIntValue(rs.getString("rulesrc"), -1);
        }
        String expinfosql = "select * from rule_expressionbase where id=" + expid;        
        rs.executeSql(expinfosql);
        if (rs.next()) {
            expbean = new ExpressionBean();
            expbean.setId(Util.getIntValue(rs.getString("id")));
            expbean.setDatafield(Util.getIntValue(rs.getString("datafield")));
            expbean.setDatafieldlabel(Util.null2String(rs.getString("datafieldtext")));
            expbean.setTypehrm(Util.getIntValue(rs.getString("typehrm"), -1));
            expbean.setHtmltype(Util.null2String(rs.getString("htmltype")));
            expbean.setFieldtype(Util.null2String(rs.getString("fieldtype")));
            expbean.setDbtype(Util.null2String(rs.getString("dbtype")));
            expbean.setCompareoption1(Util.getIntValue(rs.getString("compareoption1"), -1));
            expbean.setCompareoption2(Util.getIntValue(rs.getString("compareoption2"), -1));
            expbean.setElementtext1(Util.null2String(rs.getString("elementlabel1")));
            expbean.setElementvalue1(Util.null2String(rs.getString("elementvalue1")));
            expbean.setElementvalue2(Util.null2String(rs.getString("elementvalue2")));
            expbean.setParamtype(Util.getIntValue(rs.getString("paramtype"), -1));
            expbean.setValuetype(Util.getIntValue(rs.getString("valuetype"), -1));
            expbean.setRedius(Util.null2String(rs.getString("redius")));
            expbean.setNodeId(Util.null2String(rs.getString("nodeId")));
            expbean.setMeetCondition(Util.null2String(rs.getString("meetCondition")));
            expbean.setJingdu(Util.null2String(rs.getString("jingdu")));
            expbean.setWeidu(Util.null2String(rs.getString("weidu")));
            expbean.setRulesrc(Util.getIntValue(""+rulesrc, -1));
        }
        return expbean;
    }

}



